package com.wyj.wuliwuli.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wyj.wuliwuli.common.AjaxRequest;
import com.wyj.wuliwuli.common.AjaxResult;
import com.wyj.wuliwuli.common.CommonValue;
import com.wyj.wuliwuli.common.PageParam;
import com.wyj.wuliwuli.entity.*;
import com.wyj.wuliwuli.entity.mapper.*;
import com.wyj.wuliwuli.service.WuliVideoService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
@Service
public class WuliVideoServiceImpl implements WuliVideoService {

    private final WuliVideoMapper wuliVideoMapper;
    private final WuliNoticeMapper wuliNoticeMapper;
    private final WuliUserMapper wuliUserMapper;
    private final WuliVideoCommentMapper wuliVideoCommentMapper;
    private final WuliVideoCommentDetailMapper wuliVideoCommentDetailMapper;
    private final WuliUserVideoLikeMapper wuliUserVideoLikeMapper;

    /**
     * 分页查询
     *
     * @param ajaxRequest
     * @return
     */
    @Override
    public AjaxResult page(AjaxRequest<PageParam> ajaxRequest) {
        JSONObject params = ajaxRequest.getParams();
        String title = params.getString("title");
        String type = params.getString("type");
        // 构建分页参数
        PageParam pageParam = ajaxRequest.getData();
        Pageable pageable = PageRequest.of(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getDirection(), pageParam.getProperty());
        if (StringUtils.isNotBlank(title) && StringUtils.isNotBlank(type)) {
            Page<WuliVideo> page = wuliVideoMapper.findByTitleLikeAndTypeAndAuditStatus(title, type, 1, pageable);
            return AjaxResult.ok(page);
        }
        if (StringUtils.isNotBlank(type)) {
            Page<WuliVideo> page = wuliVideoMapper.findAllByTypeAndAuditStatus(type, 1, pageable);
            return AjaxResult.ok(page);
        }
        // 构建条件参数
        WuliVideo video = new WuliVideo();
        video.setTitle(title);
        video.setAuditStatus(1);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // 设置字符串匹配方式：模糊查询
                .withIgnoreCase(true) // 忽略大小写
                .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains()) // 设置模糊查询字段：title
                .withIgnoreNullValues(); // 忽略null值字段
        Example<WuliVideo> example = Example.of(video, matcher);
        Page<WuliVideo> page = wuliVideoMapper.findAll(example, pageable);
        return AjaxResult.ok(page);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult getById(Long id) {
        if (id == null) {
            return AjaxResult.fail("ID不能为空");
        }
        Optional<WuliVideo> videoOptional = wuliVideoMapper.findById(id);
        if (!videoOptional.isPresent()) {
            return AjaxResult.fail("ID为" + id + "的视频不存在或已被删除，请刷新后重试");
        }

        return AjaxResult.ok(videoOptional.get());
    }

    /**
     * 保存（包括修改和新增）
     *
     * @param ajaxRequest
     * @return
     */
    @Override
    public AjaxResult save(AjaxRequest<WuliVideo> ajaxRequest) {
        WuliVideo video = ajaxRequest.getData();
        String checkMsg = this.saveCheck(video);
        if (StringUtils.isNotBlank(checkMsg)) {
            return AjaxResult.fail(checkMsg);
        }
        wuliVideoMapper.save(video);
        if (video.getAuthor().getRole().equals(CommonValue.Role.ADMIN)) {
            List<WuliUser> userList = wuliUserMapper.findByRole(CommonValue.Role.USER);
            for (WuliUser user : userList) {
                WuliNotice notice = new WuliNotice();
                notice.setVideo(video);
                notice.setUser(user);
                notice.setIsRead(0);
                wuliNoticeMapper.save(notice);
            }
        }
        return AjaxResult.ok(video);
    }

    /**
     * 保存前检查数据合规性
     * @param wuliVideo 视频对象
     * @return 报错信息
     */
    public String saveCheck(WuliVideo wuliVideo) {
        if (wuliVideo == null) {
            return "请求数据不能为空";
        }
        if (StringUtils.isBlank(wuliVideo.getPath())) {
            return "路径不能为空";
        }
        if (wuliVideo.getAuthor() == null) {
            return "作者不能为空";
        }
        Long userId = wuliVideo.getAuthor().getId();
        if (userId == null) {
            return "作者不能为空";
        }
        WuliUser author = wuliUserMapper.getById(userId);
        if (author == null) {
            return "作者不存在";
        }
        wuliVideo.setAuthor(author);
        if (StringUtils.isBlank(wuliVideo.getType())) {
            return "视频类型不能为空";
        }
        if (StringUtils.isBlank(wuliVideo.getTitle())) {
            return "视频主题不能为空";
        }
        return null;
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult deleteById(Long id) {
        if (id == null) {
            return AjaxResult.fail("ID不能为空");
        }
        if (wuliVideoMapper.existsById(id)) {
          List<WuliUserVideoLike> list1 = wuliUserVideoLikeMapper.findAllByVideo_Id(id);
          for (WuliUserVideoLike like:list1) {
              wuliUserVideoLikeMapper.deleteById(like.getId());
          }
          List<WuliVideoComment> list2 = wuliVideoCommentMapper.findAllByVideo_Id(id);
          for (WuliVideoComment comment:list2) {
              List<WuliVideoCommentDetail> list3 = wuliVideoCommentDetailMapper.findByComment_Id(comment.getId());
              for(WuliVideoCommentDetail detail:list3) {
                  wuliVideoCommentDetailMapper.deleteById(detail.getId());
              }
              wuliVideoCommentMapper.deleteById(comment.getId());
          }

            wuliVideoMapper.deleteById(id);
        } else {
            return AjaxResult.fail("ID为" + id + "的视频不存在或已被删除，请刷新后重试");
        }
        return AjaxResult.of();
    }

    @Override
    public AjaxResult getByUserId(Long userId) {
        List<WuliVideo> list = wuliVideoMapper.findAllByAuthor_Id(userId);
        return AjaxResult.ok(list);
    }

    @Override
    public AjaxResult getByAuditStatus() {
        List<WuliVideo> list = wuliVideoMapper.findAllByAuditStatus(0);
        return AjaxResult.ok(list);
    }

    @Override
    public AjaxResult auditById(Long id) {
        WuliVideo wuliVideo = wuliVideoMapper.getById(id);
        wuliVideo.setAuditStatus(1);
        wuliVideoMapper.save(wuliVideo);
        return AjaxResult.of();
    }


}
